﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using SDCloudSolution.SDCloud.Entities;

namespace SDCloudSolution.SDCloud.DataLayer
{
    public static class QueryableExtensions
    {
        public static EntityCollection<TEntity> ToEntityCollection<TEntity>(this IQueryable<TEntity> query, Paging paging)
        {
            return new EntityCollection<TEntity>(paging)
            {
                EntityList = query
                    .Skip(paging.PageIndex * paging.PageSize)
                    .Take(paging.PageSize)
                    .ToList(),
                TotalCount = query.Count()
            };
        }

        public static async Task<EntityCollection<TEntity>> ToEntityCollectionAsync<TEntity>(this IQueryable<TEntity> query, Paging paging)
        {
            return new EntityCollection<TEntity>(paging)
            {
                EntityList = await query
                    .Skip(paging.PageIndex * paging.PageSize)
                    .Take(paging.PageSize)
                    .ToListAsync(),
                TotalCount = await query.CountAsync()
            };
        }
    }
}
